package com.qef.com.mmovie.fragment;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Fade;
import android.transition.Slide;
import android.util.Log;
import android.view.View;

import com.nightonke.boommenu.BoomMenuButton;
import com.orhanobut.logger.Logger;
import com.qef.com.mmovie.MainActivity;
import com.qef.com.mmovie.R;
import com.qef.com.mmovie.base.BaseFragment;
import com.qef.com.mmovie.base.DetailTransition;
import com.qef.com.mmovie.components.EventUtil;
import com.qef.com.mmovie.entity.ItemListBean;
import com.qef.com.mmovie.entity.SubscriptionDetailsEntity;
import com.qef.com.mmovie.mvp.adapter.RecyclerViewAnimator;
import com.qef.com.mmovie.mvp.adapter.SubscriptionDetailsAdapter;
import com.qef.com.mmovie.mvp.adapter.VideoAdapter;
import com.qef.com.mmovie.presenter.SubscriptionDetailsPresenter;
import com.qef.com.mmovie.presenter.contract.SubscriptionDetailsContract;
import com.qef.com.mmovie.widget.BuilderManager;
import com.qef.com.mmovie.widget.EndLessOnScrollListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;

/**
 * Created by qianenfan on 17/2/27.
 */

public class SubscriptionDetailsFragment extends BaseFragment<SubscriptionDetailsPresenter> implements SubscriptionDetailsContract.View {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.bmb)
    BoomMenuButton bmb;
    private String date;
    private SubscriptionDetailsAdapter adapter;
    private List<SubscriptionDetailsEntity.ItemListEntityX> mVideoListBean;
    private int start;
    private int num = 6;

    public static SubscriptionDetailsFragment newInstance() {
        Bundle bundle = new Bundle();
        SubscriptionDetailsFragment videoFragment = new SubscriptionDetailsFragment();
        videoFragment.setArguments(bundle);
        return videoFragment;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.video_home_fragment;
    }

    @Override
    protected void initEventAndData() {
        setupWindowAnimations();
        initBoomMenu();
        refresh.setBackgroundColor(getResources().getColor(R.color.page4));
        refresh.setProgressViewOffset(false, 100, 200);
        refresh.setRefreshing(true);
        refresh.setOnRefreshListener(() -> {
            refresh.setRefreshing(true);
            mPresenter.getVideoData(start =0, num);
        });

        LinearLayoutManager layout = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(layout);
        mVideoListBean = new ArrayList<>();

        adapter = new SubscriptionDetailsAdapter(getActivity(), mVideoListBean);
        adapter.setOnItemClickListener((position, view, vh) -> {

//                startChildFragment(mVideoListBean.get(position)
//                , (VideoAdapter.MyHolder) vh)

//                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(FirstActivity.this, v, "button").toBundle());
//            Pair<View, String> imagePair = Pair.create(((VideoAdapter.MyHolder) vh).imageView, getString(R.string.image_transition));
//            Pair<View, String> textPair = Pair.create(((VideoAdapter.MyHolder) vh).textView, getString(R.string.title));
//            Pair<View, String> textPairx = Pair.create(((VideoAdapter.MyHolder) vh).description, getString(R.string.description));
//            ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
//                    imagePair, textPair, textPairx);
//            startActivity(new Intent(getActivity(), VideoDetailActivity.class).
//                            putExtra(VideoDetailActivity.VIDEO_INFOS, mVideoListBean.get(position).getData())
//                    , compat.toBundle());


        });


//        final Pair<View, String>[] pairs = TransitionHelper.createSafeTransitionParticipants(getActivity(), true);
//        startActivity(target, pairs, sample);

//        recycler.setAdapter(RecyclerViewAnimator.setAnimator(adapter));
        recycler.setAdapter(RecyclerViewAnimator.setAnimator(adapter));
//        //设置item的载入动画
        recycler.setItemAnimator(new SlideInLeftAnimator());
        recycler.getItemAnimator().setAddDuration(400);
        recycler.getItemAnimator().setRemoveDuration(400);
        recycler.getItemAnimator().setMoveDuration(400);
        recycler.getItemAnimator().setChangeDuration(400);
        recycler.addOnScrollListener(new EndLessOnScrollListener(layout, 0) {
            @Override
            public void onLoadMore() {
                start += 6;
                mPresenter.getVideoData(start, num);
            }
        });
        mPresenter.getVideoData(start = 0, num);
    }

    private void setupWindowAnimations() {
        // Re-enter transition is executed when returning to this activity
//        Slide slideTransition = new Slide();
//        slideTransition.setSlideEdge(Gravity.LEFT);
//        slideTransition.setDuration(500);
//        Explode enterTransition = new Explode();
//        enterTransition.setDuration(500);
        Fade enterTransition = new Fade();
        enterTransition.setDuration(500);
        // This view will not be affected by enter transition animation
        enterTransition.excludeTarget(R.id.img_detail, true);
        getActivity().getWindow().setReenterTransition(enterTransition);
//        getActivity().getWindow().setExitTransition(slideTransition);
    }


    @NonNull
    private ScaleInAnimationAdapter getScaleInAnimationAdapter() {
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter);
        ScaleInAnimationAdapter scaleInAnimationAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        alphaAdapter.setDuration(800);
        alphaAdapter.setFirstOnly(false);
        scaleInAnimationAdapter.setFirstOnly(false);
        return scaleInAnimationAdapter;
    }

    @Override
    public void showContent(SubscriptionDetailsEntity videoListBean) {
        Logger.i("-------------->");
        if (refresh.isRefreshing()) {
            refresh.setRefreshing(false);
            mVideoListBean.clear();
            adapter.clear();
            adapter.addAll(videoListBean.getItemList());
//            recycler.setAdapter(adapter);
        } else {
            adapter.addAll(videoListBean.getItemList());
        }
        mVideoListBean.addAll(videoListBean.getItemList());

//        int end = videoListBean.getNextPageUrl().lastIndexOf("&num");
//        int start = videoListBean.getNextPageUrl().lastIndexOf("start=");
//        date = videoListBean.getNextPageUrl().substring(start, videoListBean.getNextPageUrl().length()).toString();

    }

    private void initBoomMenu() {
        bmb.setVisibility(View.GONE);
        for (int i = 0; i < bmb.getPiecePlaceEnum().pieceNumber(); i++)
            bmb.addBuilder(BuilderManager.getSimpleCircleButtonBuilder());
    }

    private void startChildFragment(ItemListBean videoListBean, VideoAdapter.MyHolder vh) {
        EventUtil.sendEvent(true + "");
        VideoDetailFragment fragment = VideoDetailFragment.newInstance(
                videoListBean.getData());
        // 这里是使用SharedElement的用例

        // LOLLIPOP(5.0)系统的 SharedElement支持有 系统BUG， 这里判断大于 > LOLLIPOP
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            setExitTransition(new Fade());
            fragment.setEnterTransition(new Slide());
            fragment.setSharedElementReturnTransition(new DetailTransition());
            fragment.setSharedElementEnterTransition(new DetailTransition());

            // 25.1.0以下的support包,Material过渡动画只有在进栈时有,返回时没有;
            // 25.1.0+的support包，SharedElement正常
            fragment.transaction()
                    .addSharedElement(vh.imageView, getString(R.string.image_transition))
//                        .addSharedElement(((VideoAdapter.MyHolder) vh).textView,"tv")
                    .commit();
        }
        start(fragment);
        ((MainActivity) getActivity()).hindbar();
    }

    @Override
    public void error(Throwable throwable) {
        Log.e("oye", "error: ", throwable);
    }
}
